package com.mymarkdown.app.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author zenglun
 * @date 2021/12/10 11:41 上午
 * @description: TODO
 */
@Slf4j
public class ReadFileImageUtil {

    public static void showImage(String imagePath, HttpServletResponse response) throws IOException {
        if (StrUtil.isEmpty(imagePath)) {
            return;
        }
        //获取文件名
        File file = new File(imagePath);
        if (!file.exists()){
            return;
        }
        //设置缓存时间31536000 365天，此处代码防止图片抖动
        response.setHeader("Cache-Control", "max-age=31536000");

        //
        log.info("[ReadFileImageUtil]--[showImage],image图片地址为:{}", file.getPath());
        BufferedImage bufferedImage = ImageIO.read(file);

        ImageIO.write(bufferedImage, FileUtil.extName(file), response.getOutputStream());
    }
}
